package cn.HuanG.order.service.impl;

import cn.HuanG.base.constant.PayBillConstants;
import cn.HuanG.base.service.impl.BaseServiceImpl;
import cn.HuanG.order.domain.OrderAddress;
import cn.HuanG.order.domain.OrderProduct;
import cn.HuanG.order.domain.OrderProductDetail;
import cn.HuanG.order.mapper.OrderAddressMapper;
import cn.HuanG.order.mapper.OrderProductDetailMapper;
import cn.HuanG.order.service.IOrderProductService;
import cn.HuanG.org.domain.Product;
import cn.HuanG.org.domain.Shop;
import cn.HuanG.org.mapper.ProductMapper;
import cn.HuanG.org.mapper.ShopMapper;
import cn.HuanG.pay.domain.AlipayInfo;
import cn.HuanG.pay.domain.PayBill;
import cn.HuanG.pay.mapper.AlipayInfoMapper;
import cn.HuanG.pay.mapper.PayBillMapper;
import cn.HuanG.pay.service.IPayService;
import cn.HuanG.quartz.domain.QuartzJobInfo;
import cn.HuanG.quartz.service.IQuartzService;
import cn.HuanG.user.domain.User;
import cn.HuanG.user.domain.UserAddress;
import cn.HuanG.user.mapper.UserAddressMapper;
import cn.HuanG.util.CodeGenerateUtils;
import cn.HuanG.util.DistanceUtil;
import cn.HuanG.util.LoginContext;
import cn.HuanG.util.Point;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class OrderProductServicImpl  extends BaseServiceImpl<OrderProduct>  implements IOrderProductService {
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private UserAddressMapper userAddressMapper;
    @Autowired
    private OrderAddressMapper orderAddressMapper;
    @Autowired
    private PayBillMapper payBillMapper;
    @Autowired
    private AlipayInfoMapper alipayInfoMapper;
    @Autowired
    private IPayService iPayService;
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private IQuartzService quartzService;
    @Autowired
    private OrderProductDetailMapper orderProductDetailMapper;
    @Override
    public String createOrderProduct(Map<String, String> map, HttpServletRequest request) {
        /*
         * 	product_id:this.product.id//领养宠物
         * 	address_id:1,//要配送的地址
         * 	payMethod:'ALIPAY'//支付方式
         */
        System.out.println("请求头"+request);
        //1、获取product_id
        Long product_id = Long.valueOf(map.get("product_id"));
        //2、获取店铺地址
        Long address_id = Long.valueOf(map.get("address_id"));
        //3、获取支付方式
        String ALIPAY = map.get("payMethod");
        //1、根据用户选择的配送地址，查询出userAddress
        UserAddress userAddress = userAddressMapper.queryById(address_id);
        //根据用户选择的地址，选择最近门店的id
//        // 1.把用户地址解析 票point
        Point point = DistanceUtil.getPoint(userAddress.getAddress());
//        // 2.查询全部门店，调用方法找到距离最近的门店
        List<Shop> shops = shopMapper.queryAll();
        Shop shop = DistanceUtil.getNearestShop(point, shops);
        System.out.println("shopid1："+shop.getId());
        //获取最近门店地址
        String address = shop.getAddress();
//        //设置最近的门店到useraddress表里面
        userAddress.setFullAddress(address);
        //保存数据
        userAddressMapper.save(userAddress);
        //2、查询选择服务
        Product product = productMapper.queryById(product_id);
        //3、product  生成一个Orderproduct保存
        OrderProduct orderProduct = product2OrderProduct(product,request,shop);
        //保存数据
        super.save(orderProduct);
        //8、生成快照单
        OrderProductDetail orderProductDetail = product2OrderProductDetail(product);
       //设置快照单号
        orderProductDetail.setOrder_id(orderProduct.getId());
        //设置productid
        orderProductDetail.setProduct_id(product.getId());
        //保存数据返回主键id
        orderProductDetailMapper.save(orderProductDetail);
       //4、根据用户的地址  生成一个OrderAddress保存
        OrderAddress orderAddress =  userAddress2orderAdress(userAddress);
        //需要维护的sn
        orderAddress.setOrderSn(orderProduct.getOrderSn());
        //需要维护adopt_id
        orderAddress.setOrder_id(orderAddress.getId());
        //保存数据并返回主键,因为在上面保存adopt时没有address，所以在address保存后，有了主键，才能保存在adopt表中
        orderAddressMapper.save(orderAddress);
        super.update(orderProduct);
        //5、生成一个支付订单
        PayBill payBill = orderProduct2payBill(orderProduct);
        payBill.setPayChannel(ALIPAY);
        payBill.setMoney(orderProduct.getPrice());
        payBill.setCreateTime(new Date());
        payBillMapper.save(payBill);
        //6、使用支付宝支付，把值传回去
        System.out.println("表表id："+orderProduct.getShop_id());
        AlipayInfo alipayInfo = alipayInfoMapper.queryByShopId(orderProduct.getShop_id());
        System.out.println("支付表表："+alipayInfo);
        String result = iPayService.pay(payBill, alipayInfo);
        //7、增加对应的定时任务
        Map<String, Object> paramsMap = new HashMap<>();
        System.out.println("订单号"+payBill.getOrderSn());
        paramsMap.put("orderSn",payBill.getOrderSn());
        //设置时间表达式，调用方法
        QuartzJobInfo info = new QuartzJobInfo();
        info.setJobName(payBill.getOrderSn());
        info.setParams(paramsMap);
        info.setFireDate(payBill.getLastPayTime());

        quartzService.addJob(info);
        return result;
    }

    private OrderProductDetail product2OrderProductDetail(Product product) {
        OrderProductDetail orderProductDetail = new OrderProductDetail();
        BeanUtils.copyProperties(product,orderProductDetail);
        orderProductDetail.setCreatetime(new Date());
        return orderProductDetail;
    }

    private PayBill orderProduct2payBill(OrderProduct orderProduct) {
        PayBill payBill = new PayBill();
        //因两个表数据大致相同直接copy
        BeanUtils.copyProperties(orderProduct,payBill);
        //需要设置：setBusinessKey,setBusinessType,setPayChannel(支付方式)在上面,setCreateTime 时间,setMoney  钱
        payBill.setBusinessKey(orderProduct.getId());
        payBill.setBusinessType(PayBillConstants.ORDER_PRODUCT);
        return payBill;
    }

    private OrderAddress userAddress2orderAdress(UserAddress userAddress) {
        OrderAddress orderAddress= new OrderAddress();
        //使用方法copy参数第一位是数据源，第二位是目标
        BeanUtils.copyProperties(userAddress,orderAddress);
        return  orderAddress;
    }

    private OrderProduct product2OrderProduct(Product product, HttpServletRequest request,Shop shop) {
        OrderProduct orderProduct = new OrderProduct();
        orderProduct.setDigest("【宠物窝窝】-服务订单");
//        private Integer state;  订单状态
        orderProduct.setState(0);
        //        private Long user_id;
        User current = (User) LoginContext.getCurrent(request);
        orderProduct.setUser_id(current.getId());
//        private BigDecimal price; 售价
        orderProduct.setPrice(product.getSaleprice());
//        private String orderSn;
        //调用工具类传入登录用户的id
        String s = CodeGenerateUtils.generateOrderSn(current.getId());
        orderProduct.setOrderSn(s);
//        private String paySn;
//        private Date lastPayTime; 最后支付时间
        orderProduct.setLastPayTime(new Date(System.currentTimeMillis()+1000*60*1));
//        private Date lastConfirmTime;
//        private Long pet_id;
        orderProduct.setProduct_id(product.getId());
        System.out.println("shopid2："+shop.getId());
        orderProduct.setShop_id(shop.getId());
//        private Long address_id;
        return  orderProduct;
    }
}
